package utils

import (
	"errors"
	"fmt"
	"time"

	"github.com/dgrijalva/jwt-go/v4"
)

var MySecret = []byte("heckman.cn")

type User struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

type CustomClaims struct {
	User
	jwt.StandardClaims
}

// 创建 Token
func GenToken(user User) (string, error) {
	claim := CustomClaims{
		user,
		jwt.StandardClaims{
			ExpiresAt: jwt.At(time.Now().Add(time.Hour * 24)), //5分钟后过期
			Issuer:    "heckman",                              //签发人
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
	return token.SignedString(MySecret)
}

func GetTokenUser(token string) (User, error) {
	userclaim, err := ParseToken(token)
	if err != nil {
		fmt.Println("解析token异常", err)
		return User{}, err
	} else {
		user := User{}
		user.Username = userclaim.Username
		return user, err
	}
}

// 解析 token
func ParseToken(tokenStr string) (*CustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenStr, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		return MySecret, nil
	})
	if err != nil {
		fmt.Println(" token parse err:", err)
		return nil, err
	}
	if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
		return claims, nil
	}
	return nil, errors.New("invalid token")
}
